public class LeetCode {
    public int[] sortArray(int[] nums) {
        mergeSort(nums,0,nums.length-1);
        return nums;
    }
    public void mergeSort(int[] nums,int left,int right){
        if(left>=right){
            return;
        }
        //1.划分中间节点
        int mid = (left+right)/2;
        //2.左右区间排序
        mergeSort(nums,left,mid);
        mergeSort(nums,mid+1,right);
        //3.合并两个数组
        int[] tmp = new int[right-left+1];
        int cur1 = left,cur2 = mid+1,i=0;
        while(cur1<=mid && cur2<=right){
            tmp[i++] = nums[cur1]<=nums[cur2]?nums[cur1++]:nums[cur2++];
        }
        while(cur1<=mid){
            tmp[i++] = nums[cur1++];
        }
        while(cur2<=right){
            tmp[i++] = nums[cur2++];
        }
        //4.还原
        for (int j = left; j <= right; j++) {
            nums[j] = tmp[j-left];
        }
    }
    int count = 0;
    int tmp[];
    public int reversePairs(int[] record) {
        tmp = new int[record.length];
        mergeSort1(record,0,record.length-1);
        return count;
    }
    public void mergeSort1(int[] nums,int left,int right){
        if(left>=right){
            return;
        }
        int mid = (left+right)/2;
        mergeSort1(nums,left,mid);
        mergeSort1(nums,mid+1,right);

        int cur1 = left,cur2 = mid+1,i=0;
        while(cur1<=mid && cur2<=right){
            if(nums[cur1]<=nums[cur2]){
                tmp[i++] = nums[cur1++];
            }else{
                tmp[i++] = nums[cur2++];
                count+=mid-cur1+1;
            }
        }
        while (cur1<=mid){
            tmp[i++] = nums[cur1++];
        }
        while(cur2<=right){
            tmp[i++] = nums[cur2++];
        }
        for (int j = left; j <= right; j++) {
            nums[j] = tmp[j-left];
        }
    }
}
